﻿using System.Drawing;
using System.Windows.Forms;

using FreeImageAPI;

using RayDen.Library.Core.Primitives;
using RayDen.SceneLab.UI;

namespace RayDen.SceneLab.Controllers.FormControllers
{
    public class ImageEditorController : EditorControllerBase<ImageEditorForm, Bitmap>
    {
        private Bitmap bmp;
        public string ImageName { get; set; }

        public ImageEditorController(Form owner) : base(owner)
        {
        }

        public void OpenFile(string fileName)
        {
            bmp = new FreeImageBitmap(fileName).ToBitmap();
            {
                this.State.Reset(bmp);
                this.ImageName = fileName;

            }
        }


        public void OpenEthalonFile(string fileName)
        {
            EthalonImage = new FreeImageBitmap(fileName).ToBitmap();
        }


        public void SaveFile(string fileName)
        {
            
        }



        public void Dispose()
        {
            if (bmp != null)
            {
                bmp.Dispose();
            }
            if (EthalonImage != null)
            {
                EthalonImage.Dispose();
            }
        }

        public Image Image { get { return bmp; } }

        public Bitmap EthalonImage { get; set; }


        public string EvaluateError()
        {
            if (Image == null || EthalonImage == null)
            {
                return "Images arent setuped";
            }
            double variance = 0;

            for (int y = 0; y < Image.Height; y++)
            {
                for (int x = 0; x < Image.Width; x++)
                {
                    var cA = RgbSpectrum.Create(bmp.GetPixel(x, y));
                    var cE = RgbSpectrum.Create(EthalonImage.GetPixel(x, y));
                    variance += (cE.y() - cA.y())*(cE.y() - cA.y());
                }
            }

            variance /= (Image.Height*Image.Width);

            return string.Format("Image Variance {0:F10}", variance);
        }

    }
}
